package com.item.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.item.mapper.AdminMapper;
import com.item.mapper.ArticleMapper;
import com.item.pojo.Article;
import com.item.pojo.User;
import com.item.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleMapper articleMapper;

    @GetMapping
    public List<Article> selectAll(){
        return articleService.selectAll();
    }

    @GetMapping("/selectById/{id}")
    public Article selectById(@PathVariable Integer id){
        return articleService.selectById(id);
    }

    @GetMapping("/collect")
    public List<Article> selectByCollect(){
        return articleService.selectByCollect();
    }

    @GetMapping("/selectByTitle/{title}")
    public List<Article> selectByType(@PathVariable String title){
        return articleService.selectByType(title);
    }


    @GetMapping("/hotList")
    public List<Article> selectHotList(){
        return articleMapper.selectHotList();
    }

    @GetMapping("/pageList")
    public Map<String,Object> pageList(@RequestParam Integer page, @RequestParam Integer pageSize,
                                       @RequestParam String title,@RequestParam String type ){
        Map<String,Object> map =  articleService.pageList(pageSize,page,title,type);
        return map;
    }

    @PostMapping
    public Object update(@RequestBody Article article){
        return articleService.update(article);
    }

    @PutMapping
    public int insert(@RequestBody Article article){
        return articleService.insert(article);
    }



    @DeleteMapping("/{id}")
    public int delete(@PathVariable Integer id){
        int delete = articleService.delete(id);
        return delete;
    }

    //批量删除
    @PostMapping("/del/batch")
    public int delBatch(@RequestBody List<Integer> ids){
        return articleService.delBatch(ids);
    }


    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Article> list = articleService.selectAll();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("文章信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        //List<User> list = reader.readAll(User.class);
        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Article> articles = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Article article=new Article();
            article.setTitle(row.get(1).toString());
            article.setContent(row.get(2).toString());
            article.setType(row.get(3).toString());
            article.setAdd((Integer) row.get(4));
            article.setCollect((Integer) row.get(5));
            article.setComment((Integer) row.get(6));
            article.setImgUrl(row.get(7).toString());
            articles.add(article);
        }

        articleService.insertBatch(articles);
        return true;
    }
}
